package com.nulldev.util.dataManagement.preferencesAPI;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;

import com.nulldev.util.data.Variables;
import com.nulldev.util.dataManagement.preferencesAPI.fdf_legacy.LegacyFDFPreferences;
import com.nulldev.util.dataManagement.preferencesAPI.legacy.LegacyAPIPreferences;
import com.nulldev.util.dataManagement.preferencesAPI.plist.PreferenceList;
import com.nulldev.util.io.IOUtils;

public class Preferences implements Closeable {

	private PreferenceInterface<?> prefs;
	private final PreferencesType type;

	public Preferences(final PreferencesType type) {
		Variables.notNullE(type);
		this.type = type;
	}

	public PreferencesType getType() {
		return this.type;
	}

	public void open(final File file) throws IOException {
		switch (this.type) {
			case LEGACY_PREFERENCES: {
				this.prefs = new LegacyAPIPreferences(file);
				break;
			}
			case FORMATTED_DATA_FILE_LEGACY:
				try {
					this.prefs = new LegacyFDFPreferences(file);
					break;
				} catch (Exception e) {
					throw new IOException(e);
				}
			case PREFERENCES_LIST: {
				this.prefs = new PreferenceList(file);
				break;
			}
			default:
				throw new UnsupportedOperationException("Unsupported preferences type: " + this.type);
		}
	}

	@Override
	public void close() throws IOException {
		IOUtils.closeQuietly(this.prefs);
	}
}
